<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QR Scanner and QR Code Generator</title>
    <script src="https://cdn.jsdelivr.net/npm/qrcodejs/qrcode.min.js" defer></script>
    <script src="dist/js/framework.js" async></script>
    <style>
        :root {
            --colour-1: #000000;
            --colour-2: #ccc;
            --colour-3: #e4d4ff;
            --colour-4: #f0f0f0;
            --colour-5: #181818;
            --colour-6: #242424;
            --accent: #8b3dff;
            --blur-bg: #16101b66;
            --blur-border: #84719040;
            --background: #16101b;
            --text-color: #e4d4ff;
            --border-color: #84719040;
            --button-bg: #242424;
            --button-hover: #181818;
            --button-text: #e4d4ff;
            --border-radius: 8px;
        }

        /* Light theme */
        body.white {
            --colour-1: #ffffff;
            --colour-3: #212529;
            --accent: #007bff;
            --blur-bg: transparent;
            --blur-border: #ccc;
            --background: #ffffff;
            --text-color: #212529;
            --border-color: #ccc;
            --button-bg: #f0f0f0;
            --button-hover: #e0e0e0;
            --button-text: #212529;
        }

        body { 
            font-family: Arial, sans-serif; 
            text-align: center; 
            margin: 20px; 
            background-color: var(--background);
            color: var(--text-color);
            transition: background-color 0.3s, color 0.3s;
        }
        
        video { 
            width: 400px; 
            height: 400px; 
            border: 1px solid var(--border-color); 
            display: block; 
            margin: auto; 
            object-fit: cover; 
            max-width: 100%;
            border-radius: var(--border-radius);
        }
        
        #qrcode { 
            margin-top: 20px; 
            background-color: white;
            padding: 10px;
            display: none;
            border-radius: var(--border-radius);
        }
        
        #qrcode img, #qrcode canvas { 
            margin: 0 auto; 
            width: 400px; 
            height: 400px; 
            max-width: 100%;
        }
        
        button { 
            margin: 5px; 
            padding: 10px; 
            background-color: var(--button-bg);
            color: var(--button-text);
            border: 1px solid var(--border-color);
            border-radius: var(--border-radius);
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        button:hover {
            background-color: var(--button-hover);
        }
        
        button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        h1, h2 {
            color: var(--text-color);
        }
        
        a {
            color: var(--accent);
            text-decoration: none;
        }
        
        a:hover {
            text-decoration: underline;
        }
        
        #cam-status, #qrcode-status {
            margin: 10px 0;
            padding: 5px;
            border-radius: var(--border-radius);
            background-color: var(--blur-bg);
            border: 1px solid var(--blur-border);
        }

        #qrcode-status {
            display: inline-block;
        }
    </style>
</head>
<body>

    <h1>QR Scanner & QR Code</h1>
    
    <h2>QR Code Scanner</h2>
    <video id="video"></video>
    <button id="startCamera">Start Camera</button>
    <button id="stopCamera">Stop Camera</button>
    <button id="switchCamera">Switch Camera</button>
    <button id="toggleFlash">Toggle Flash</button>
    <p id="cam-status"></p>

    <h2>QR Code</h2>
    <div id="qrcode"></div>
    <p><a id="qrcode-status" target="_parent"></a></p>
    <button id="generateQRCode">Generate QR Code</button>

    <script type="module">
        const conversation_id = window.location.hash.replace("#", "");
        if (!conversation_id) {
            document.getElementById('generateQRCode')
                .setAttribute('disabled', 'disabled');
        }

        import QrScanner from 'https://cdn.jsdelivr.net/npm/qr-scanner/qr-scanner.min.js';
        
        const videoElem = document.getElementById('video');
        const camStatus = document.getElementById('cam-status');
        let qrScanner;

        // Function to synchronize the theme
        (() => {
            const isDarkMode = localStorage.getItem("darkMode") !== "false";
            if (isDarkMode) {
                document.body.classList.remove("white");
            } else {
                document.body.classList.add("white");
            }
        })();

        document.getElementById('stopCamera').addEventListener('click', () => {
            if (currentStream) {
                currentStream.getTracks().forEach(track => track.stop());
            }
            if (qrScanner) {
                qrScanner.stop();
            }
        });

        document.getElementById('toggleFlash').addEventListener('click', async () => {
            if (qrScanner) {
                const hasFlash = await qrScanner.hasFlash();
                if (hasFlash) {
                    qrScanner.toggleFlash();
                } else {
                    alert('Flash not supported on this device.');
                }
            }
        });
        let share_id = null;
        document.getElementById('generateQRCode').addEventListener('click', async () => {
            if (share_id) {
                localStorage.removeItem(`conversation:${share_id}`);
                const delete_url = `${window.backendUrl}/backend-api/v2/files/${encodeURIComponent(share_id)}`;
                await fetch(delete_url, {
                    method: 'DELETE'
                });
            }
            let conversation = JSON.parse(localStorage.getItem(`conversation:${conversation_id}`));
            if (!conversation.share) {
                conversation.share = conversation.id;
                share_id = crypto.randomUUID();
                conversation.id = share_id;
                conversation.updated = Date.now();
                localStorage.setItem(`conversation:${share_id}`, JSON.stringify(conversation));
            }
            const url = `${window.backendUrl}/backend-api/v2/chat/${encodeURIComponent(conversation.id)}`;
            const response = await fetch(url, {
                method: 'POST',
                headers: {'content-type': 'application/json'},
                body: JSON.stringify(conversation)
            });
            const share = `${window.location.origin}/chat/#${encodeURIComponent(conversation.id)}`;
            const qrcodeStatus = document.getElementById('qrcode-status');
            if (response.status !== 200) {
                qrcodeStatus.innerText = 'Error generating QR code: ' + response.statusText;
                return;
            }
            qrcodeStatus.innerText = share;
            qrcodeStatus.href = share;
            document.getElementById("qrcode").innerHTML = '';
            document.getElementById("qrcode").style.display = 'inline-block';
            const qrcode = new QRCode(
                document.getElementById("qrcode"),
                share,
            {
                width: 400,
                height: 400,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            });
        });

        const switchButton = document.getElementById('switchCamera');
        let currentStream = null;
        let facingMode = 'environment';

        async function startCamera() {
            try {
                document.querySelectorAll(".scan-region-highlight").forEach(e => e.remove());
                if (currentStream) {
                    currentStream.getTracks().forEach(track => track.stop());
                }

                const constraints = {
                    video: {
                        width: { ideal: 800 },
                        height: { ideal: 800 },
                        facingMode: facingMode
                    },
                    audio: false
                };

                const stream = await navigator.mediaDevices.getUserMedia(constraints);
                currentStream = stream;
                video.srcObject = stream;
                video.play();

                qrScanner = new QrScanner(videoElem, result => {
                    camStatus.innerText = 'Camera Success: ' + result.data;
                    console.log('decoded QR code:', result);
                    if (result.data.startsWith(window.location.origin)) {
                        window.parent.location = result.data;
                    }
                }, {
                    highlightScanRegion: true,
                    highlightCodeOutline: true,
                });
                await qrScanner.start();
            } catch (error) {
                console.error('Error accessing the camera:', error);
                alert(`Could not access the camera: ${error.message}`);
            }
        }

        switchButton.addEventListener('click', () => {
            facingMode = facingMode === 'user' ? 'environment' : 'user';
            startCamera();
        });

        document.getElementById('startCamera').addEventListener('click', () => {
            startCamera();
        });
    </script>
</body>
</html>
